package com.meichis.yndms.vm;

import android.util.ArrayMap;

import com.google.gson.reflect.TypeToken;
import com.meichis.mcsappframework.utils.DateUtil;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.yndms.common.DataCenter;
import com.meichis.yndms.http.CallSubscriber;
import com.meichis.yndms.http.IWebServiceCallback;
import com.meichis.yndms.http.RetrofitUtil.RxSchedulersHelper;
import com.meichis.yndms.model.DicDataItem;
import com.meichis.yndms.model.VisitTemplate;
import com.meichis.yndms.repository.ApiUtil;
import com.meichis.yndms.repository.manager.BaseManager;
import com.meichis.yndms.room.AppDatabase;

import java.util.ArrayList;
import java.util.List;

public class SyncBaseDataPresenter extends BaseManager {

    private List<SyncData> syncDatas = new ArrayList<>();
    private SyncBaseDataListener mListener;
    private int totalCount;

    public SyncBaseDataPresenter() {
        this(new SyncBaseDataListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onNext(SyncData data) {

            }

            @Override
            public void onComplete() {

            }
        });
        long lastUpdateTime = SharePreferenceUtil.getInstance().getLongValue(SharePreferenceUtil.PREFERENCES_LASTUPDATETIME);
        if (lastUpdateTime == 0
                || !DateUtil.CompareDate(DateUtil.getDay(System.currentTimeMillis()), DateUtil.getDay(lastUpdateTime), DateUtil.FORMAT_YMD)) {
            setSyncDatas(getAllSyncDatas());
        }
    }

    public SyncBaseDataPresenter(SyncBaseDataListener listener) {
        mListener = listener;
    }

    public List<SyncData> getAllSyncDatas() {
        List<SyncData> syncDatas = new ArrayList<>();
        syncDatas.add(SyncData.字典数据);
        syncDatas.add(SyncData.拜访模板);
        return syncDatas;
    }

    public void setSyncDatas(List<SyncData> syncDatas) {
        this.syncDatas.clear();
        this.syncDatas.addAll(syncDatas);
    }

    public void sync() {
        mListener.onStart();
        if (syncDatas.size() == 0) {
            mListener.onComplete();
            return;
        }
        totalCount = syncDatas.size();

        if (syncDatas.contains(SyncData.字典数据)) {
            GetDicByTableNamesJson();
        }

        if (syncDatas.contains(SyncData.拜访模板)) {
            GetVisitTemplateList();
        }
    }

    private void GetVisitTemplateList() {
        ArrayMap<String, Object> hs = new ArrayMap<>();
        //MDS经销商ID
        hs.put("TDP", 1002);
        getRootApi().RequestSFA(getToken(), ApiUtil.getRequestPack(hs, "PBMService.GetVisitTemplateList"))
                .compose(RxSchedulersHelper.rxSchedulerHelper())
                .subscribe(new CallSubscriber(new TypeToken<List<VisitTemplate>>() {
                }.getType(), new IWebServiceCallback<List<VisitTemplate>>() {
                    @Override
                    public void onSucceed(int sequence, List<VisitTemplate> resultPack, String ReturnInfo, int Return) {
                        AppDatabase.getInstance().visitTemplateDao().deleteAll();
                        if (resultPack != null && resultPack.size() >= 0) {
                            for (VisitTemplate template : resultPack) {
                                template.setOwnerClient(DataCenter.Manufacturer);
                            }
                            AppDatabase.getInstance().visitTemplateDao().insert(resultPack);
                        } else {
                            MessageTools.showLongToast("暂无数据！");
                        }
                        complete(SyncData.拜访模板);
                    }

                    @Override
                    public void onFailure(int sequence, int errorCode, String error) {
                        complete(SyncData.拜访模板);
                        MessageTools.showLongToast(error);
                    }
                }));
    }

    private void GetDicByTableNamesJson() {
        ArrayMap<String, Object> hs = new ArrayMap<>();
        //MDS经销商ID
        hs.put("TDP", DataCenter.Manufacturer);
        getRootApi().RequestSFA(getToken(), ApiUtil.getRequestPack(hs, "PublicService.GetDicByTableNamesJson"))
                .compose(RxSchedulersHelper.rxSchedulerHelper())
                .subscribe(new CallSubscriber(new TypeToken<List<DicDataItem>>() {
                }.getType(), new IWebServiceCallback<List<DicDataItem>>() {
                    @Override
                    public void onSucceed(int sequence, List<DicDataItem> resultPack, String ReturnInfo, int Return) {

                        if (resultPack != null && resultPack.size() >= 0) {
                            AppDatabase.getInstance().dicDataItemDao().insertAll(resultPack);
                        } else {
                            MessageTools.showLongToast("暂无数据！");
                        }
                        complete(SyncData.字典数据);
                    }

                    @Override
                    public void onFailure(int sequence, int errorCode, String error) {
                        complete(SyncData.字典数据);
                        MessageTools.showLongToast(error);
                    }
                }));
    }

    private void complete(SyncData data) {
        mListener.onNext(data);
        totalCount--;
        if (totalCount == 0) {
            mListener.onComplete();
            SharePreferenceUtil.getInstance().setLongValue(SharePreferenceUtil
                    .PREFERENCES_LASTUPDATETIME, System.currentTimeMillis());
        }
    }


    public enum SyncData {
        字典数据, 拜访模板
    }


    public interface SyncBaseDataListener {
        void onStart();

        void onNext(SyncData data);

        void onComplete();
    }
}
